package com.d3works.apps.businessproject.db.repo;

import com.d3works.apps.account.db.Invoice;
import com.d3works.apps.businessproject.db.InvoicingProject;
import com.d3works.apps.businessproject.service.app.AppBusinessProjectService;
import com.d3works.apps.project.db.ProjectTask;
import com.d3works.apps.project.db.repo.ProjectTaskRepository;
import com.d3works.apps.supplychain.db.repo.InvoiceSupplychainRepository;
import com.d3works.common.ObjectUtils;
import com.d3works.inject.Beans;
import java.util.List;

public class InvoiceProjectRepository extends InvoiceSupplychainRepository {

  @Override
  public void remove(Invoice entity) {

    if (Beans.get(AppBusinessProjectService.class).isApp("business-project")) {
      List<InvoicingProject> invoiceProjectList =
          Beans.get(InvoicingProjectRepository.class)
              .all()
              .filter("self.invoice.id = ?", entity.getId())
              .fetch();
      List<ProjectTask> projectTaskList =
          Beans.get(ProjectTaskRepository.class)
              .all()
              .filter("self.invoiceLine.invoice = ?1", entity)
              .fetch();
      if (ObjectUtils.notEmpty(projectTaskList)) {
        for (ProjectTask projectTask : projectTaskList) {
          projectTask.setInvoiceLine(null);
        }
      }
      for (InvoicingProject invoiceProject : invoiceProjectList) {
        invoiceProject.setInvoice(null);
        invoiceProject.setStatusSelect(InvoicingProjectRepository.STATUS_DRAFT);
      }
    }

    super.remove(entity);
  }
}
